//
//  GSetViewController.m
//  penzer
//
//  Created by caiyc on 2018/10/13.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "GSetViewController.h"
#import "ChangeRoleViewController.h"
#import "EditInfoViewController.h"
#import "ContactsViewController.h"
#import "LoginViewController.h"
#import <AVFoundation/AVFoundation.h>
//#import "YWAddressViewController.h"
#import "AddressListViewController.h"
#import "AboutViewController.h"
#import "SuggsetViewController.h"
#import "ResetPassViewController.h"
#import "SecutyViewController.h"
#import "AppDelegate.h"

@interface GSetViewController ()<UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIScrollView *botom_ScroView;
@property (weak, nonatomic) IBOutlet UIImageView *icon;
@property (weak, nonatomic) IBOutlet UIButton *selectBtn;
- (IBAction)selectimg:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *mobile;
@property(nonatomic,strong)UIImagePickerController *imagePicke;
@property(nonatomic,strong)UIImage *icons;

@end

@implementation GSetViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setNavigation:1 andTitle:@"设置" andNaviColor:nil andTitleColor:nil andRightimg:@"" andsel:@selector(set)];
    self.botom_ScroView.contentSize = CGSizeMake(0, screen_height*1.1);
    self.botom_ScroView.showsVerticalScrollIndicator = 0;
    self.icon.layer.cornerRadius = 5;
    self.icon.layer.masksToBounds = 1;
    self.selectBtn.layer.borderWidth = 0.8;
    self.selectBtn.layer.borderColor =[UIColor blackColor].CGColor;
    self.selectBtn.layer.cornerRadius = 5;
    self.selectBtn.layer.masksToBounds = 1;
    self.icon.layer.cornerRadius = 45;
    self.icon.layer.masksToBounds = 1;
    // Do any additional setup after loading the view from its nib.
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if([XTool GetDefaultInfo:USER_INFO]){
        NSDictionary *userDic = [XTool GetDefaultInfo:USER_INFO];
        NSLog(@".......%@",userDic);
        NSURL *url = [NSURL URLWithString:userDic[@"avatar"]];
        [self.icon sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"Bitmap"]];
        self.nickName.text = [userDic[@"nickname"]isEqualToString:@""]?@"暂无":userDic[@"nickname"];
        NSString *newStr = [XTool setMobileToCharters:userDic[@"mobile"]];
        self.mobile.text = newStr;
    }
}


#pragma mark--退出登录
- (IBAction)exit:(id)sender {
    [[NSNotificationCenter defaultCenter]postNotificationName:STOPTIMENOTO object:nil];
    [XTool SaveDefaultInfo:nil Key:USER_INFO];
    // LoginViewController *vc = [[LoginViewController alloc]init];
    [APPDELEGATE goComenLoginWithRoleType:RoleType_YH targetVc:self];
    
}


#pragma mark--切换身份
- (IBAction)changeRole:(id)sender {
    ChangeRoleViewController *vc = [[ChangeRoleViewController alloc]init];
    [self pushSecondVC:vc];
}




#pragma mark--选择照片完成
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    //NSLog(@"选择的图片回调%@",info);
    NSLog(@"相册:%@",info);
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
     [self.imagePicke dismissViewControllerAnimated:YES completion:nil];
    self.icon.image = image;
    self.icons = image;
    [self uploadimg];
}



- (IBAction)selectimg:(UIButton *)sender
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            [WToast showWithText:@"相机功能受限，请检查"];
        }else{
            NSString * mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
            {
                [WToast showWithText:@"相机没权限，请在设置里面打开"];
                //没权限
                return ;
            }
            else if(!self.imagePicke)
            {
                self.imagePicke = [[UIImagePickerController alloc]init];
                self.imagePicke.sourceType = UIImagePickerControllerSourceTypeCamera;
                self.imagePicke.delegate = self;
                
                [self.imagePicke showsCameraControls];
                self.imagePicke.allowsEditing = YES;
               // [self.imagePicke setAllowsEditing:1];
                [self presentViewController:self.imagePicke animated:YES completion:nil];
            }
            else
            {
                self.imagePicke.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePicke animated:YES completion:nil];
            }
        }
        
        
    }];
    UIAlertAction *libra = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
        {
            [WToast showWithText:@"相机没权限，请在设置里面打开"];
            return ;
        }
        
        
        if(self.imagePicke)
        {
            self.imagePicke.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        else
        {
            self.imagePicke = [[UIImagePickerController alloc]init];
            self.imagePicke.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            self.imagePicke.delegate = self;
        }
        self.imagePicke.allowsEditing = YES;
        [self presentViewController:self.imagePicke animated:YES completion:nil];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [self presentViewController:alert animated:YES completion:nil];
    [alert addAction:camera];
    [alert addAction:libra];
    [alert addAction:cancel];
    
}



//
- (IBAction)func_Action:(UIButton *)sender
{
    NSInteger index = sender.tag;
    ContactsViewController *vc = [[ContactsViewController alloc]init];
    switch (index) {
        case 0:{
            EditInfoViewController *vc = [[EditInfoViewController alloc]init];
            [self pushSecondVC:vc];
            return;
            break;
        }
        case 1:{
            SecutyViewController *vc = [[SecutyViewController alloc]init];
            [self pushSecondVC:vc];
            return;
            break;
        }
        case 2:{
            AddressListViewController *vc = [[AddressListViewController alloc]init];
            [self pushSecondVC:vc];
            return;
            break;
        }
        case 3:{
            vc.title = @"通用";
            break;
        }
        case 4:{
            SuggsetViewController *vc = [[SuggsetViewController alloc]init];
            [self pushSecondVC:vc];
            return;
            break;
        }
        case 5:{
            AboutViewController *vc = [[AboutViewController alloc]init];
            [self pushSecondVC:vc];
            return;
            //vc.title = @"关于";
            //        YWAddressViewController *addressVC = [[YWAddressViewController alloc] init];
            //        // 保存后的地址回调
            //        addressVC.addressBlock = ^(YWAddressInfoModel *model) {
            //            NSLog(@"用户地址信息填写回调：");
            //            NSLog(@"姓名：%@", model.nameStr);
            //            NSLog(@"电话：%@", model.phoneStr);
            //            NSLog(@"地区：%@", model.areaAddress);
            //            NSLog(@"详细地址：%@", model.detailAddress);
            //            NSLog(@"是否设为默认：%@", model.isDefaultAddress ? @"是" : @"不是");
            //        };
            //        [self pushSecondVC:addressVC];
            break;
        }
    }
//    [self pushSecondVC:vc];
}


#pragma mark--更新服务器用户信息
-(void)uploadimg
{
    NSDictionary *userDic = [XTool GetDefaultInfo:USER_INFO];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", nil]];
    NSDictionary *paramter = @{@"c":@"entry",@"i":@"10",@"ac":@"member",@"ctrl":@"live",@"token":[XTool GetDefaultInfo:USER_INFO][@"token"],@"op":@"member",@"m":@"bz_activities",@"ta":@"edit_member",@"sex":userDic[@"sex"],@"weigth":userDic[@"weigth"],@"birthday":userDic[@"birthday"],@"height":userDic[@"height"],@"nickname":userDic[@"nickname"]};
    
    NSLog(@"发布参数：%@",paramter);
    
    [manager POST:BASE_URL parameters:paramter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //        for(NSInteger i = 0; i < self.image_Array.count; i++) {
        if(self.icons){
            NSData * imageData = UIImageJPEGRepresentation(self.icons, 0.5);
            // 上传的参数名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            //}
        }
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"上传回调===%@",responseObject);
        
        if([[responseObject objectForKey:@"message"][@"resultCode"]integerValue]==0){
            [WToast showWithText:@"修改成功"];
            [self loadinfo];
        }else{
            [WToast showWithText:responseObject[@"message"][@"resultMessage"]];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WToast showWithText:@"更改失败请重试"];
        //  NSLog(@"上传失败原因===%@",error);
    }];
}


#pragma mark--更新本地用户信息
-(void)loadinfo
{
    NSDictionary *param = @{@"ta":@"get_member",@"op":@"member",@"ac":@"member",@"ctrl":@"live"};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            NSDictionary *dic = [NSDictionary changeType:response[@"data"]];
            [XTool SaveDefaultInfo:dic Key:USER_INFO];
            NSDictionary *userDic = [XTool GetDefaultInfo:USER_INFO];
            NSLog(@".......%@",userDic);
            NSURL *url = [NSURL URLWithString:userDic[@"avatar"]];
            [self.icon sd_setImageWithURL:url];
            //  [self.navigationController popViewControllerAnimated:NO];
        }
    } failure:^(NSError *error) {
        
    }];
}


@end
